<template>
  <div>
    <el-form-item label="友情链接">
      <el-button type="primary" @click="handleAdd" link>添加链接</el-button>
    </el-form-item>
    <div v-if="editorForm.friend" class="friend-editor">
      <el-scrollbar max-height="200px">
        <draggable class="drag-area" v-model="editorForm.friend.value" :group="{ name: 'g1', pull: true, put: true }"
          item-key="id" handle=".friend-item-left" animation="150">
          <template #item="{ element: item, index }">
            <div>
              <div class="friend-item" :class="{ 'is-active': activeId === item.id }" @mouseenter="activeId = item.id"
                @mouseleave="activeId = null">
                <div class="friend-item-left">
                  <div class="friend-index">{{ index + 1 }}</div>
                  <div class="friend-name" :title="item.name">{{ item.name }}</div>
                </div>
                <div v-show="activeId === item.id" class="friend-item-right">
                  <el-icon :size="12" @click="handleDelete(item.id)">
                    <Delete />
                  </el-icon>
                  <el-icon :size="12" @click="handleEdit(item)">
                    <Edit />
                  </el-icon>
                </div>
              </div>
              <div class="children-container">
                <NestedDraggable v-if="editorForm.friend.nested" v-model="item.children" v-model:activeId="activeId"
                  :level="1" @delete="handleDelete" @edit="handleEdit" />
              </div>
            </div>
          </template>
        </draggable>
      </el-scrollbar>
      <el-dialog v-model="dialogShow" :title="friendForm.id ? '编辑友情链接' : '添加友情链接'" width="500px" @close="resetForm">
        <el-form ref="friendFormRef" :model="friendForm" label-width="80px" label-position="right">
          <el-form-item label="名称" prop="name">
            <el-input v-model="friendForm.name" placeholder="请输入单位名称"></el-input>
          </el-form-item>
          <el-form-item label="链接" prop="url">
            <el-input v-model="friendForm.url" placeholder="请输入官网链接"></el-input>
          </el-form-item>
          <el-form-item label="打开位置" prop="open">
            <el-radio-group v-model="friendForm.open" class="ml-4">
              <el-radio label="_blank">新窗口</el-radio>
              <el-radio label="self">当前窗口</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="logo" prop="logo">
            <div class="form-img" @click="showBackImageUpload = true">
              <div class="has-img" v-if="friendForm.logo">
                <img :src="friendForm.logo" alt="" />
                <span @click.stop="handleRemoveImg">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </div>
              <el-icon v-else>
                <Plus />
              </el-icon>
            </div>
            <FilesUpload v-model:showDialog="showBackImageUpload" :limit="1" @getFileList="handleGetCoverImg" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="friendForm.description" type="textarea" :rows="3" placeholder=""></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogShow = false">取消</el-button>
            <el-button type="primary" @click="handleConfirm">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, inject, reactive, watch } from 'vue'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'

const { editorForm, backUpdate } = inject('commonForm')
watch(() => editorForm.value.friend, () => {
  backUpdate()
}, { deep: true })
// 添加链接
const dialogShow = ref(false)
const friendFormRef = ref(null)
const defaultFriendForm = reactive({
  id: '',
  name: '',
  url: '',
  logo: '',
  description: '',
  open: '_blank',
  children: []
})
const friendForm = ref(Object.assign({}, defaultFriendForm))
const handleAdd = () => {
  dialogShow.value = true
}
const activeId = ref(null)
const handleEdit = row => {
  activeId.value = row.id
  friendForm.value = Object.assign({}, row)
  dialogShow.value = true
}
const handleDelete = id => {
  editorForm.value.friend.value = deleteById(editorForm.value.friend.value, id)
}
const deleteById = (tree, id) => {
  return tree
    .filter(node => node.id !== id)
    .map(node => ({
      ...node,
      children: deleteById(node.children || [], id)
    }))
}
const handleConfirm = () => {
  if (friendForm.value.id) {
    const friend = findById(editorForm.value.friend.value, friendForm.value.id)
    Object.assign(friend, friendForm.value)
  } else {
    friendForm.value.id = Date.now()
    editorForm.value.friend.value.push(friendForm.value)
  }
  dialogShow.value = false
}
const findById = (tree, id) => {
  for (const node of tree) {
    if (node.id === id) {
      return node // 找到匹配的 id，返回节点
    }
    if (node.children) {
      const found = findById(node.children, id) // 递归搜索子节点
      if (found) {
        return found // 如果在子节点中找到，返回找到的节点
      }
    }
  }
  return null // 如果没有找到，返回 null
}
const resetForm = () => {
  friendFormRef.value.clearValidate()
  friendForm.value = Object.assign({}, defaultFriendForm)
}
// 添加logo
const showBackImageUpload = ref(false)
const handleGetCoverImg = imgList => {
  friendForm.value.logo = imgList[0].url
}
// 移除图片
const handleRemoveImg = () => {
  friendForm.value.logo = ''
}
</script>

<style lang="scss" scoped>
.friend-editor {
  margin-top: -15px;
  width: 100%;

  .friend-item {
    display: flex;
    justify-self: space-between;
    align-items: center;
    margin-bottom: 4px;
    padding: 8px;
    border-radius: 4px;
    background: rgba(#ccc, 0.2);
    font-size: 12px;
    color: #606266;

    &.is-active {
      background-color: $focusContent;
    }

    .friend-item-left {
      display: flex;
      align-items: center;
      width: 70%;
      padding: 0 10px;
      cursor: move;

      .friend-index {
        flex-shrink: 0;
        position: relative;
        width: 30px;
      }

      .friend-name {
        flex: 1;
        overflow: hidden;
        @include textEllipsis(12px, 1);
      }
    }

    .friend-item-right {
      display: flex;
      justify-content: end;
      align-items: center;
      padding-right: 10px;
      width: 30%;

      .el-icon {
        margin-left: 5px;
        cursor: pointer;
      }
    }
  }
}

.form-img {
  height: 100px;
  width: 150px;
  border: 1px dashed $borderColor;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;

  .has-img {
    height: 100%;
    width: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;

    img {
      max-width: 100%;
      max-height: 100%;
    }

    span {
      display: none;
      position: absolute;
      right: 0;
      top: 0;
      background-color: $failColor;
      height: 20px;
      width: 20px;
      font-size: 18px;
      color: #fff;
    }

    &:hover {
      span {
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.children-container {
  min-height: 10px;
  margin-left: 20px;
  border-radius: 4px;
  transition: all 0.3s;
}

:deep(.sortable-drag) {
  opacity: 0.5;
}

:deep(.sortable-ghost) {
  opacity: 0.2;
  background: $mainColor;
}
</style>